<?php

class myUser extends sfBasicSecurityUser {
    

    public function initialize(sfEventDispatcher $dispatcher, sfStorage $storage, $options = array()) {
        parent::initialize($dispatcher, $storage, $options);

        $context = sfContext::getInstance();

        if ($context->getRequest()->isXmlHttpRequest() && !$this->isAuthenticated()) {
            // Escaping View Rendering and Sending Only Headers
            sfContext::getInstance()->getConfiguration()->loadHelpers('Url');
            $login_module = sfConfig::get('sf_login_module');
            $login_action = sfConfig::get('sf_login_action');
            $output = "window.location='" . url_for($login_module.'/'.$login_action) . "'";

            $context->getResponse()->setHttpHeader("X-JSON", $output);
            $context->getController()->setRenderMode(sfView::RENDER_NONE);
        }
    }

    public function signIn($username) {
        $c=new Criteria();
        $c->add(AdminPeer::KORISNICKO_IME,$username, Criteria::EQUAL);
        $admin = AdminPeer::doSelectOne($c);

        $this->setAttribute('user_id', $admin->getId(), 'user');
        
        $this->setAuthenticated(true);
        
        
        // Create the key and save it as a cookie
        $cookie_name = sfConfig::get('app_app_user_cookie_name', 'ets_presence') . '_' . sfConfig::get('sf_app');
        $cookie_key = date('YmdHis') . substr((string)microtime(), 1, 8);
        $cookie_expiration = sfConfig::get('app_app_user_cookie_name_expiration', 1800);

        sfContext::getInstance()->getResponse()->setCookie($cookie_name, md5($cookie_key), time() + $cookie_expiration);
    }

    public function signOut() {
        $this->getAttributeHolder()->removeNamespace('user');

        $this->setAuthenticated(false);
        

        $cookie_name = sfConfig::get('app_app_user_cookie_name', 'ets_presence') . '_' . sfConfig::get('sf_app');
        $cookie_expiration = sfConfig::get('app_app_user_cookie_name_expiration', 1800);
        sfContext::getInstance()->getResponse()->setCookie($cookie_name, '', time() - $cookie_expiration);
    }

    public function getId() {
        return $this->getAttribute('user_id', '', 'user');
    }

    public function getKupacObj() {
        return KupacPeer::retrieveByPk($this->getId());
    }



    
    
}
